package com.nian.message.rocketmq.producer;

import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用途：
 * 开发：zhangmj
 * 日期：2020/4/6 21:03
 */
@RestController
public class TestController {

    @Autowired
    IRocketMQProducer iRocketMQProducer;

    @GetMapping("producer/test")
    public Map producerTest() {

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String body = "RocketMQ 生产者测试消息：时间： " + sdf.format(new Date()) + ".";
            SendResult sendResult = iRocketMQProducer.send("producer_topic_test", "test", body);
            return createMap(0, "success", sendResult);
        } catch (Exception e) {
            e.printStackTrace();
            return createMap(1, "fail", e.getMessage());
        }
    }

    @GetMapping("producer/test/x")
    public Map producerTestA() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String body = "RocketMQ 生产者测试【事务】消息：时间： " + sdf.format(new Date()) + ".";
            TransactionSendResult sendResult = iRocketMQProducer.sendMessageInTransaction("producer_topic_shiwu_test_", "shiwu_msg", body);
            return createMap(0, "success", sendResult);
        } catch (Exception e) {
            e.printStackTrace();
            return createMap(1, "fail", e.getMessage());
        }
    }

    public Map createMap(int status, String msg, Object data) {
        Map<String, Object> map = new HashMap(3);
        map.put("status", 0);
        map.put("msg", msg);
        map.put("data", data);
        return map;
    }
}
